// Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.

package collider

import (
	"log"
	"sync"
	"time"
)

// dashboard 用于收集和报告服务器的统计信息。
type dashboard struct {
	lock sync.Mutex

	startTime time.Time

	totalWs  int
	wsErrs   int
	httpErrs int
}

// statusReport 是发送给客户端的状态报告结构。
type statusReport struct {
	UpTimeSec float64 `json:"upsec"`
	OpenWs    int     `json:"openws"`
	TotalWs   int     `json:"totalws"`
	WsErrs    int     `json:"wserrors"`
	HttpErrs  int     `json:"httperrors"`
}

// newDashboard 创建一个新的 dashboard 实例。
func newDashboard() *dashboard {
	log.Println(">>> 创建新的 dashboard 实例")
	return &dashboard{startTime: time.Now()}
}

// getReport 从房间表中获取并生成状态报告。
func (db *dashboard) getReport(rs *roomTable) statusReport {
	db.lock.Lock()
	defer db.lock.Unlock()

	upTime := time.Since(db.startTime)
	return statusReport{
		UpTimeSec: upTime.Seconds(),
		OpenWs:    rs.wsCount(),
		TotalWs:   db.totalWs,
		WsErrs:    db.wsErrs,
		HttpErrs:  db.httpErrs,
	}
}

// incrWs 增加 WebSocket 连接的总数。
func (db *dashboard) incrWs() {
	db.lock.Lock()
	defer db.lock.Unlock()
	db.totalWs += 1
	log.Printf(">>> WebSocket 连接总数增加: %d", db.totalWs)
}

// onWsErr 记录一个 WebSocket 错误。
func (db *dashboard) onWsErr(err error) {
	db.lock.Lock()
	defer db.lock.Unlock()
	db.wsErrs += 1
	log.Printf("!!! WebSocket 错误计数增加: %d (错误: %v)", db.wsErrs, err)
}

// onHttpErr 记录一个 HTTP 错误。
func (db *dashboard) onHttpErr(err error) {
	db.lock.Lock()
	defer db.lock.Unlock()
	db.httpErrs += 1
	log.Printf("!!! HTTP 错误计数增加: %d (错误: %v)", db.httpErrs, err)
}
